package com.yds.dccjll.androidhome.oschina.webview;

import android.content.Intent;
import android.os.Bundle;

import com.yds.dccjll.androidhome.base.App;
import com.yds.dccjll.lib.base.util.LogUtil;
import com.yds.dccjll.lib.base.util.NoHttpUtil;
import com.yds.dccjll.lib.base.webview.WebViewActivity;

import java.util.List;

public class OschinaWebContentActivity extends WebViewActivity {

    private static final String TAG = OschinaWebContentActivity.class.getSimpleName();
    public static final String url_oauth2_authorize = "https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=oMf5KtqZr13kXrbLdJ1d&redirect_uri=http://192.168.0.101:8080/auth/oauth.html";
    public static final String url_oauth2_token = "https://www.oschina.net/action/openapi/token?client_id=oMf5KtqZr13kXrbLdJ1d&client_secret=FabhzXzy1nbkqyuZVwN7W9ZTsjorlNri&grant_type=authorization_code&redirect_uri=http://192.168.0.101:8080/auth/oauth.html&refresh_token=&dataType=json&callback=&code=";
    private OschinaWebContentJSInterface oschinaWebContentJSInterface = new OschinaWebContentJSInterface();

    private OnLoadAuthCodeListener onLoadAuthCodeListener = new OnLoadAuthCodeListener() {
        @Override
        public void onLoadAuthCodeSuccess(String authCode) {
            getAuthToken(authCode);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        mWebView.loadUrl(url_oauth2_authorize);
        oschinaWebContentJSInterface.setOnLoadAuthCodeListener(onLoadAuthCodeListener);
        mWebView.addJavascriptInterface(oschinaWebContentJSInterface, "common");
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }
    
    interface OnLoadAuthCodeListener {
        void onLoadAuthCodeSuccess(String token);
    }

    private void getAuthToken(String authCode) {
        NoHttpUtil.getInstance(App.app).asyncPostStringNoEncryptRequest(
                url_oauth2_token + authCode,
                null,
                new NoHttpUtil.CommonResponseListener() {
                    @Override
                    public void requestSuccess(List data, String msg) {
                        Intent intent = new Intent();
                        intent.putExtra("authToken", (String) data.get(0));
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public void requestFailed(String error, int loglever) {
                        LogUtil.e(TAG, "error=" + error);
                    }
                }
        );
    }
}
